package cn.klaw.module;

import com.github.yitter.idgen.YitIdHelper;
import cn.klaw.consts.ProjectEventConst;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Optional;

/**
 * 项目事件基础类
 */
@Data
@Accessors(chain = true)
public class ProjectEvent{


    /**
     * 数据
     */
    private Object source;

    /**
     * 消息ID
     */
    private Long eventId;

    /**
     * 主题
     */
    private String toptic;

    /**
     * 频道
     */
    private String channel;

    /**
     * 是否异步
     */
    private boolean async;

    /**
     * 1:集群, 2:广播, 3:本地
     * @see ProjectEventConst#EVENT_PUBLISH_MODEL_CLUSTERING
     * @see ProjectEventConst#EVENT_PUBLISH_MODEL_BROADCASTING
     * @see ProjectEventConst#EVENT_PUBLISH_MODEL_LOCAL
     */
    private int messageModel;

    /**
     * 是否事务提交后才发送
     */
    private boolean afterCommitTransaction;

    /**
     * 用户TOKEN
     */
    private String token;

    /**
     * 租户编码
     */
    private String tenantId;

    public ProjectEvent(){
    }

    public ProjectEvent(String topic, String channel, Object source) {
        this(null, topic, channel, source, null, true, false);
    }

    public ProjectEvent(Long eventId, String topic, String channel, Object source, Integer messageModel, boolean async, boolean afterCommitTransaction) {
        this.source = source;
        this.eventId = Optional.ofNullable(eventId).orElseGet(YitIdHelper::nextId);
        this.toptic =  Optional.ofNullable(topic).orElse(ProjectEventConst.DEFAULT_TOPIC_NAME);
        this.messageModel = Optional.ofNullable(messageModel).orElse(ProjectEventConst.EVENT_PUBLISH_MODEL_CLUSTERING);
        this.channel = channel;
        this.async = async;
        this.afterCommitTransaction = afterCommitTransaction;
    }

}
